#region ImportedNamespace
using System;
using System.Data;
using System.Data.SqlClient;
using BO = PHSRAG.Insight21.BusinessObjects;
using ICachePolicy = PHSRAG.Insight21.Policy.ICachePolicy;
using PHSRAG.Utility;
#endregion

namespace PHSRAG.Insight21.CDS
{
	/// <summary>
	/// Summary description for Organization.
	/// </summary>
	public class Organization: BO.BusinessObject
	{
		#region Constants
		private const string OrganizationKey = "OrganizationKey_740F7141-E64D-4aab-841D-0F2254E4E16C";
		private const string GetOrganizationSProcName = "GetOrganization";	
		private const string OrganizationTable = "FwkDomainOrganization";
		private const string Column_Name_Id = "Id";
		private const string Column_Name_Name = "Name";
		private const string Column_Name_Description = "Description";
		private const string Column_Name_ParentOrganizationID = "ParentOrganizationID";
		private const string Column_Name_ChiefCode = "ChiefCode";
		private const string Column_Name_BusinessUnitNumber = "BusinessUnitNumber";
		private const string Column_Name_FullyQualifiedName = "FullyQualifiedName";
		private const string Column_Name_FwkDomainOrganizationTypeId = "FwkDomainOrganizationTypeId";
		private const string Column_Name_IsActive = "IsActive";
		private const string Column_Name_Institution = "Institution";
		private const string Column_Name_HROAdministrator = "ProtocolAdministratorId";
		private const string Column_Name_DomainId = "DomainId";
		private const string Column_Name_InstitutionId = "InstitutionId";
		private const string Column_Name_DepartmentId = "DepartmentId";
		private const string Column_Name_UnitId = "UnitId";
		private const string Column_Name_FWANumber = "FWANumber";
		
		#endregion Constants

		#region Private Members
		private int orgId;
		private string orgName;
		private string description;
		private int parentOrganizationID;
		private string chiefCode;
		private string businessUnitNumber;
		private string fullyQualifiedName;
		private int fwkDomainOrganizationTypeId;
		private bool isActive;
		private string institution;
		private int protocolAdministratorId;
        private int animalsProtocolAdministratorId;
		private int domainId;
		private int institutionId;
		private int departmentId;
		private int unitId;
		private string fwaNumber;

		#endregion

		#region Constructor
		/// <summary>
		/// Initializes the base with the specified cache policy 
		/// </summary>
		/// <param name="cachePolicy">policy to use to cache the instance</param>
		public Organization(ICachePolicy cachePolicy) : base(cachePolicy)		
		{
			
		}
		#endregion

		#region Base Class Overrides

		/// <summary>
		/// Stores this instance using a specified key based on the Cache Policy
		/// </summary>
		public override void Cache()
		{
			CachePolicy.Cache(OrganizationKey, this);
		}

		/// <summary>
		/// Removes this instance
		/// </summary>
		public override void UnCache()
		{
			CachePolicy.UnCache(OrganizationKey);
		}

		/// <summary>
		/// Loads Organization object.
		/// </summary>
		/// <param name="connectionString">Connection string to the database</param>
		/// <param name="args">additional arguments</param>
		public override void Load(string connectionString, params object[] args)
		{			
			try
			{
				if (args.Length != 1)
					throw new Exception("Organization load requires an Organization Id");

				DataContainer = DataAccess.GetDataSet(
					connectionString,
					GetOrganizationSProcName,
					DataAccess.BuildSqlParameterArray("@Id", SqlDbType.Int, args[0]));

				DataContainer.Tables[0].TableName = OrganizationTable;

				if ( DataContainer.Tables[0].Rows.Count > 0 )
				{
					DataRow dataRow = DataContainer.Tables[0].Rows[0];

					// set the properties.						
					orgId = (int)dataRow[Column_Name_Id];
					orgName = (string)dataRow[Column_Name_Name];
					description = (string)dataRow[Column_Name_Description];
					parentOrganizationID = (int)dataRow[Column_Name_ParentOrganizationID];
					object o = dataRow[Column_Name_ChiefCode];
					chiefCode = (o == DBNull.Value) ? string.Empty : (string)o;
					o = dataRow[Column_Name_BusinessUnitNumber];
					businessUnitNumber = (o == DBNull.Value) ? string.Empty : (string)o;
					fullyQualifiedName = (string)dataRow[Column_Name_FullyQualifiedName];
					fwkDomainOrganizationTypeId = (int)dataRow[Column_Name_FwkDomainOrganizationTypeId];
					isActive = (bool)dataRow[Column_Name_IsActive];
					o = dataRow[Column_Name_Institution];
					institution = (o == DBNull.Value) ? string.Empty : (string)o;
                    o = dataRow[Column_Name_HROAdministrator];
                    protocolAdministratorId = (o == DBNull.Value) ? 0 : Convert.ToInt32(o); ; 
								
					o = dataRow[Column_Name_DomainId];
					domainId = (o == DBNull.Value) ? 0 : (int)o;
					o = dataRow[Column_Name_InstitutionId];
					institutionId = (o == DBNull.Value) ? 0 : (int)o;
					o = dataRow[Column_Name_DepartmentId];
					departmentId = (o == DBNull.Value) ? 0 : (int)o;
					o = dataRow[Column_Name_UnitId];
					unitId = (o == DBNull.Value) ? 0 : (int)o;
					o = dataRow[Column_Name_FWANumber];
					fwaNumber = (o == DBNull.Value) ? string.Empty : (string)o;
				}

			}

			catch(Exception e)
			{
				Utility.ExceptionReport.WriteToEventLog(
					"Unable to load organization record", e, true, Utility.ExceptionReport.ReportType.Error);
				throw new Exception("Organization load failed", e);
			}
		}
		#endregion

		#region Public Properties
		
		/// <summary>
		/// Gets the Organization ID
		/// </summary>
		public int Id
		{
			get{ return orgId; }			
		}

		/// <summary>
		/// Gets the Name of the Organization
		/// </summary>
		public string Name
		{
			get{ return orgName; }			
		}

		/// <summary>
		/// Gets Description of the Organization
		/// </summary>
		public string Description
		{
			get{ return description; }			
		}

		/// <summary>
		/// Gets Parent Organization ID of the Organization
		/// </summary>
		public int ParentOrganizationID
		{
			get{ return parentOrganizationID; }			
		}

		/// <summary>
		/// Gets chiefCode of the Organization
		/// </summary>
		public string ChiefCode
		{
			get{ return chiefCode; }			
		}

		/// <summary>
		/// Gets BusinessUnitNumber of the Organization
		/// </summary>
		public string BusinessUnitNumber
		{
			get{ return businessUnitNumber; }			
		}

		/// <summary>
		/// Gets Fully Qualified Name of the Organization
		/// </summary>
		public string FullyQualifiedName
		{
			get{ return fullyQualifiedName; }			
		}

		/// <summary>
		/// Gets Domain Organization Type ID
		/// </summary>
		public int FwkDomainOrganizationTypeId
		{
			get{ return fwkDomainOrganizationTypeId; }			
		}

		/// <summary>
		/// Gets Is Active flag
		/// </summary>
		public bool IsActive
		{
			get{ return isActive; }			
		}

		/// <summary>
		/// Gets institution of the Organization
		/// </summary>
		public string Institution
		{
			get{ return institution; }			
		}

		/// <summary>
		/// The AdmPersonId of the HRO Protocol administrator 
		/// responsible for ths department.
		/// </summary>
		public int ProtocolAdministratorId
		{
			get { return protocolAdministratorId; }
		}

        /// <summary>
        /// The AdmPersonId of the HRO Protocol administrator 
        /// responsible for ths department.
        /// </summary>
        public int AnimalsProtocolAdministratorId
        {
            get {
                DataTable aniamlsProtocolAdminDataTable = DataAccess.GetDataTable(Utility.DataAccess.GetConnectionString(),
                        "GetWorkflowPerson", Utility.DataAccess.BuildSqlParameterArray("@orgId", SqlDbType.Int, 2, "@workflowRole", SqlDbType.VarChar, "AnimalsProtocolAdministrator", "@workflowType", SqlDbType.VarChar, "Default"));
                if (aniamlsProtocolAdminDataTable != null)
                {
                    if ((aniamlsProtocolAdminDataTable.Rows.Count > 0) && aniamlsProtocolAdminDataTable.Columns.Contains("PersonId"))
                    {
                        animalsProtocolAdministratorId = Int32.Parse(aniamlsProtocolAdminDataTable.Rows[0]["PersonId"].ToString());
                    }
                }
                return animalsProtocolAdministratorId; 
                }
        }

		/// <summary>
		/// The FwkDomainOrganizationId of this organization's Domain.
		/// </summary>
		public int DomainId
		{
			get { return domainId; }
		}

		/// <summary>
		/// The FwkDomainOrgaizationId of this organization's Institution.
		/// </summary>
		public int InstitutionId
		{
			get { return institutionId; }
		}

		/// <summary>
		/// The FwkDomainOrgaizationId of this organization's Department.
		/// </summary>
		public int DepartmentId
		{
			get { return departmentId; }
		}

		/// <summary>
		/// The FwkDomainOrgaizationId of this organization's Unit.
		/// </summary>
		public int UnitId
		{ 
			get { return unitId; } 
		}

		/// <summary>
		/// The FWA number of the Organization - NOTE: This only 
		/// applies to Institutions, and not all may have one.
		/// </summary>
		public string FWANumber
		{
			get { return fwaNumber; }
		}
		#endregion

		#region Static Methods

		/// <summary>
		/// Formats the Fully Qualified Organization Name, supporting the following business rule:
		/// 1. If the org Name is just a domain, do nothing
		/// 2. If the org is a non-domain, strip out the domain name, and the subsequent ">"
		/// </summary>
		/// <param name="unformattedName">name to format, if necessary</param>
		/// <returns>formatted Organization name</returns>
		public static string StripDomain(string unformattedName)
		{
			int startIndex = unformattedName.IndexOf(">") + 1;
			return (startIndex >= 0) ? (unformattedName.Substring(startIndex)).Trim() : unformattedName;
		}

		#endregion

	}				   
}					   
